import Comments from '@/model/Comments'
import { getJWTPayload } from '@/common/utils'
import {checkCode} from '@/common/utils'
class CommentsController {
  constructor() {
    
  }

  async getComments (ctx) {
    const params = ctx.query
    const tid = params.tid
    if (!params.tid) {
       ctx.body = {
        code: 500,
        msg: '文章id为空'
      }
      return
    }
    const page = params.page ? params.page : 0
    const limit = params.limit ? parseInt(params.limit) : 10
    let result = await Comments.getCommentsList(tid, page, limit)

    // 判断用户是否登录，已登录的用户才去判断点赞信息
    let obj = {}
    if (typeof ctx.header.authorization !== 'undefined') {
      obj = await getJWTPayload(ctx.header.authorization)
    }
    if (typeof obj._id !== 'undefined') {
      result = result.map(item => item.toJSON())
      for (let i = 0; i < result.length; i++) {
        let item = result[i]
        item.handed = '0'
        const commentsHands = await CommentsHands.findOne({ cid: item._id, uid: obj._id })
        if (commentsHands && commentsHands.cid) {
          if (commentsHands.uid === obj._id) {
            item.handed = '1'
          }
        }
      }
    }
    const total = await Comments.queryCount(tid)
    ctx.body = {
      code: 200,
      total,
      data: result,
      msg: '查询成功'
    }
  }

  async addComment (ctx) {
    const { body } = ctx.request
    let sid = body.sid, code = body.code
    let ckCode = await checkCode(sid, code);
    if (!ckCode) {
      ctx.body = {
        code: 500,
        msg:'验证码验证失败'
      }
      return
    } else {
      const newComment = new Comments(body)
      const obj = await getJWTPayload(ctx.header.authorization)
      newComment.cuid = obj.id
      const comment = await newComment.save()
      ctx.body = {
        msg: '评论成功',
        code: 200,
        data:comment
      }
    }
  }
}

export default new CommentsController